package com.wswy.wzcx.model;

import android.content.Context;
import android.support.annotation.NonNull;
import android.text.TextUtils;

import com.che.data.MyObservable;
import com.che.libcommon.utils.JsonKit;
import com.che.libcommon.utils.RxBus;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.wswy.wzcx.AppContext;
import com.wswy.wzcx.R;
import com.wswy.wzcx.jpush.IPushOperator.OnPushOperatorCallback;
import com.wswy.wzcx.jpush.NotificationHandler;
import com.wswy.wzcx.jpush.PushChannel;
import com.wswy.wzcx.module.InternalMsgCode;
import com.wswy.wzcx.utils.ShareHelper;
import com.wswy.wzcx.utils.SharedPrefStorage;
import com.wswy.wzcx.utils.SimpleObjConvertAdapter;

import com.wswy.wzcx.module.UserDataProvider;

import io.reactivex.MaybeObserver;
import io.reactivex.SingleObserver;
import io.reactivex.disposables.Disposable;
import timber.log.Timber;

/**
 * Created by wangduheng26 on 2018/1/19.
 * wangduheng26@gmail.com
 */

public class DataCenter extends MyObservable {
    public static final String TAG = "DataCenter";
    public static final int USER_CHANGED = 0X0001;
    public static final String KEY_USER_MODE = "key.user_mode";
    public static final String KEY_LOCAL_PUSH = "key_local_push";
    public static final String KEY_SUBSCRIBE_NOTIFY = "key_subscript_notify";

    public static final String KEY_LOCAL_CHECK_UPDATE_TIME="key_local_check_update_time";
    public static final String KEY_LAST_CHECK_VERSION = "key_last_check_version";

    private UserMode userMode;
    private IWXAPI api;

    public final int[] icons = new int[]{R.drawable.gasoline_bg, R.drawable.washcar_bg, R.drawable.maintain_bg, R.drawable.weixiu_bg,
            R.drawable.che_yongpin_bg, R.drawable.chexian_bg, R.drawable.nianjian_bg, R.drawable.gaizhuang_bg};
    public static final int TYPE_COUNT = 8;
    public final String[] contents = {"加油", "洗车", "保养", "维修", "汽车用品", "车险", "年检", "改装"};

    public static DataCenter get() {
        return DataCenter.SingletonHolder.INSTANCE;
    }

    private static class SingletonHolder {
        private static final DataCenter INSTANCE = new DataCenter();
    }
    private Context context;
    private DataCenter() {
         context=AppContext.getContext();
        SimpleObjConvertAdapter<UserMode> adapter = new SimpleObjConvertAdapter<UserMode>() {
            @NonNull
            @Override
            public UserMode deserialize(@NonNull String serialized) {
                return JsonKit.GSON.fromJson(serialized, UserMode.class);
            }
        };
        SharedPrefStorage.readMessage(KEY_USER_MODE, null, adapter)
                .subscribe(new MaybeObserver<UserMode>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onSuccess(UserMode mode) {
                        if (mode != null) {
                            setUserMode(mode);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                        Timber.e(e);

                    }

                    @Override
                    public void onComplete() {

                    }
                });

    }

    public void setUserMode(UserMode userMode) {
        this.userMode = userMode;
        if (userMode != null) {
            UserDataProvider.get().init(userMode);
        } else {
            UserDataProvider.get().clear();
        }

    }

    public void updateUserMode(UserMode mode){
        if(userMode!=null){
            mode.token = userMode.token;
            saveUserMode(mode);
        }
    }

    public void saveUserModeWithoutNotify(UserMode mode){
        if (userMode != null && mode != null){
            mode.token = userMode.token;
            setUserMode(mode);
            SharedPrefStorage.writeMessage(KEY_USER_MODE, mode);
        }
    }

    public void saveUserMode(UserMode mode) {
        setUserMode(mode);
        setChanged();
        notifyObservers(USER_CHANGED, userMode);
        RxBus.getDefault().postWithCode(InternalMsgCode.CODE_LOGIN_SUCCESS,mode);
        clearChanged();
        Context context = AppContext.getContext();


        if (mode == null) {
            SharedPrefStorage.remove(KEY_USER_MODE);

            PushChannel.getHandler().deleteAlias(new OnPushOperatorCallback<String>() {
                @Override
                public void onOperatorCallback(String s) {

                }
            });

            PushChannel.getPushTagManager().updateTags();


        } else {
            SharedPrefStorage.writeMessage(KEY_USER_MODE, mode);

            PushChannel.getHandler().setAlias(mode.userAlias, new OnPushOperatorCallback<String>() {
                @Override
                public void onOperatorCallback(String s) {
                    Timber.d("onOperatorCallback --> setAlias "+s);
                }
            });

            PushChannel.getPushTagManager().updateTags();
        }
    }

    public void cleanUser() {
        UserMode userMode = this.userMode;
        if(userMode == null){
            userMode = new UserMode();
        }
        RxBus.getDefault().postWithCode(InternalMsgCode.CODE_LOGOUT,userMode);
        setUserMode(null);
        SharedPrefStorage.remove(KEY_USER_MODE);

        PushChannel.getHandler().deleteAlias(new OnPushOperatorCallback<String>() {
            @Override
            public void onOperatorCallback(String s) {

            }
        });
    }

    public UserMode getUserMode() {
        return userMode;
    }

    public boolean hasLogin() {
        return userMode != null && !TextUtils.isEmpty(userMode.token);
    }


    public IWXAPI getWXApi() {
        if (api == null) {
            initWx();
        }
        return api;
    }
    private void initWx() {
        try {
            api = WXAPIFactory.createWXAPI(context, null);
            api.registerApp(ShareHelper.WX_APP_ID);
        } catch (Exception e) {
            Timber.e(e,"wechat registerApp ex--->");
        }
    }
}
